<template>
    <div class="app-container">
        <!---搜索-->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="音频名称" prop="audioName">
                <el-input v-model="queryParams.audioName" placeholder="请输入音频名称" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="音频状态" clearable>
                    <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="音频类型" prop="audioType">
                <el-select v-model="queryParams.audioType" placeholder="音频类型" clearable>
                    <el-option v-for="dict in dict.type.audio_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete">删除</el-button>
            </el-col>
        </el-row>

        <!--表单信息-->
        <el-table :data="audioList" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="音频名称" align="center" prop="audioName" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="音频地址" align="center" prop="url" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="音频类型" align="center" prop="audioType">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.audio_type" :value="scope.row.audioType" />
                </template>
            </el-table-column>
            <el-table-column label="创建者" align="center" prop="createBy" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="status" align="center" label="状态">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250px">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="audioStart(scope.row)"
                        v-if="scope.row.audioStatus === 0">播放</el-button>
                    <el-button type="primary" size="small" @click="audioPause(scope.row)"
                        v-if="scope.row.audioStatus === 1">暂停</el-button>
                    <el-button type="primary" size="small" @click="audioResume(scope.row)"
                        v-if="scope.row.audioStatus === 2">继续播放</el-button>
                    <el-button type="danger" size="small" @click="editStatus(scope.row)"
                        v-if="scope.row.status == 0">禁用</el-button>
                    <el-button type="primary" size="small" @click="editStatus(scope.row)" v-else>启用</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--添加对话框-->
        <el-dialog title="添加音频" :visible.sync="open" width="500px" append-to-body>
            <el-form :model="form" ref="form" :rules="rules" label-width="80px">
                <el-form-item label="音频名称" prop="audioName">
                    <el-input v-model="form.audioName" placeholder="请输入音频名称"></el-input>
                </el-form-item>
                <el-form-item label="音频类型" prop="audioType">
                    <el-select v-model="form.audioType" placeholder="请选择音频类型" clearable>
                        <el-option v-for="dict in dict.type.audio_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="音频文件">
                    <el-upload :class="{ uoloadSty: showBtnDealImg, disUoloadSty: noneBtnImg }" ref="upload" action="#"
                        multiple :limit="mainImgLimit" :file-list="mainImgIds" :on-preview="handleMainImgPreview"
                        :on-change="OnChangeMainImg" :on-remove="handleRemoveMainImg" :on-exceed="handleExceedMainImg"
                        :auto-upload="false">
                        <button type="primary" size="small" padding-left="100px">点击上传</button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                            dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确定</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-dialog>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
    </div>
</template>

<script>
import { listAudio, insertAudio, removeAudio, setAudioStatus, uploadProductImg, getNumByAudioType } from "@/api/audio/audio";
export default {
    name: 'Audio',
    dicts: ["sys_normal_disable", "audio_type"],
    data() {
        return {
            // 创建一个音频
            audio: new Audio(),
            // 播放标识
            audioObj: {
                audioId: undefined,
                play: false
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            videoPrefix: process.env.VUE_APP_VIDEO_BASE_URL,
            // 总条数
            total: 0,
            //表格数据
            audioList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // edit: false,
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                audioName: undefined,
                status: undefined,
                audioType: undefined
            },
            // 表单参数
            form: {},
            mainImgIds: [], //绑定商品主图的图片数组
            showBtnDealImg: true,
            noneBtnImg: false, //是否隐藏主图上传图片的加号
            mainImageUrl: [], //主图图片路径
            mainDialogVisible: false, //放大预览图片时是否显示弹出层
            mainImgLimit: 9,
            // 表单校验
            rules: {
                audioName: [
                    { required: true, message: "音频名称不能为空", trigger: "blur" },
                ],
                audioType: [
                    { required: true, message: "请选择音频类型", trigger: "change" },
                ],
                status: [
                    { required: true, message: "请选择状态", trigger: "change" },
                ]
            },
        };
    },
    created() {
        this.getList();
    },

    methods: {
        /**查询音频列表*/
        getList() {
            this.loading = true;
            listAudio(this.queryParams).then(
                (res) => {
                    this.audioList = res.data.content;
                    this.total = res.data.totalSize;
                    this.loading = false;
                }
            );
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加音频";
        },
        /** 提交按钮*/
        submitForm: function () {
            if (
                this.mainImgIds != null &&
                this.mainImgIds != "" &&
                this.mainImgIds != undefined &&
                this.mainImgIds.length > 0
            ) {
                var arr = [];
                this.mainImgIds.forEach((item) => {
                    arr.push(item.name);
                    this.form.url = arr.join(",");
                });
            }
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    insertAudio(this.form).then((res) => {
                        this.$modal.msgSuccess("添加成功");
                        this.open = false;
                        this.mainImgIds = [];
                        this.form = {};
                        this.getList();
                    })
                }
            })
        },
        /** 删除按钮操作*/
        handleDelete(row) {
            const audioIds = row.audioId || this.ids;
            this.$modal.confirm("是否删除编号为" + audioIds + "的数据？")
                .then(function () {
                    return removeAudio(audioIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        /** 启用/禁用音频状态*/
        editStatus(row) {
            let text = row.status === "0" ? "禁用" : "启用";
            let status = row.status === "0" ? "1" : "0";

            if (status === "1") {
                getNumByAudioType(row.audioType).then((res) => {
                    if (res.data.data === 1) {
                        this.$modal.msgWarning("请至少保证每种类型下都有一个音频！")
                    } else {
                        this.$modal.confirm("是否确认" + text + "该音频")
                            .then(() => {
                                let data = {
                                    audioId: row.audioId,
                                    status: status
                                }
                                let that = this
                                setAudioStatus(data).then(() => {
                                    that.getList();
                                    that.$modal.msgSuccess(text + "成功");
                                })
                            })
                    }
                })
            } else {
                this.$modal.confirm("是否确认" + text + "该音频")
                    .then(() => {
                        let data = {
                            audioId: row.audioId,
                            status: status
                        }
                        let that = this
                        setAudioStatus(data).then(() => {
                            that.getList();
                            that.$modal.msgSuccess(text + "成功");
                        })
                    })
            }
        },
        /**播放音频按钮*/
        audioStart(row) {

            if (this.audioObj.play === false) {
                this.audioObj = {
                    audioId: row.audioId,
                    play: true
                }
                this.audio.src = this.videoPrefix + row.url;
                this.audio.autoplay = true;
                // 更新音频播放状态
                row.audioStatus = 1;

                // 绑定播放完毕事件,每次放完了可以做一些收尾的事
                this.audio.addEventListener('ended', () => {
                    row.audioStatus = 0;
                    this.audioObj = {
                        play: false
                    }
                });
            } else {
                for (let i = 0; i < this.audioList.length; i++) {
                    if (this.audioList[i].audioId === this.audioObj.audioId) {
                        this.audioList[i].audioStatus = 0
                        this.audio.pause()
                    }
                }
                this.audioObj = {
                    audioId: row.audioId,
                    play: true
                }
                this.audio.src = this.videoPrefix + row.url;
                this.audio.autoplay = true;
                // 更新音频播放状态
                row.audioStatus = 1;

                // 绑定播放完毕事件,每次放完了可以做一些收尾的事
                this.audio.addEventListener('ended', () => {
                    row.audioStatus = 0;
                    this.audioObj = {
                        play: false
                    }
                });
            }
        },
        /**暂停音频按钮*/
        audioPause(row) {
            row.audioStatus = 2;
            this.audio.pause();
        },
        /**继续播放音频按钮*/
        audioResume(row) {
            row.audioStatus = 1;
            this.audio.play();
        },
        // 表单重置
        reset() {
            this.form = {
                audioId: undefined,
                audioName: undefined,
                audioType: undefined,
                status: "0",
            };
            this.resetForm("form");
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.audioId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        //预览图片时
        handleMainImgPreview(file) {
            this.mainImageUrl = file.url;
            this.mainDialogVisible = true;
        },
        /**将图片上传到服务器 */
        //根据图片数量，判断上传按钮是否显示
        OnChangeMainImg(file, fileList) {
            let formData = new FormData(); //  用FormData存放上传文件
            formData.append("file", file.raw);
            let that = this;
            uploadProductImg(formData).then((response) => {
                if (this.mainImgIds === undefined) {
                    this.mainImgIds = [];
                }
                that.mainImgIds.push({
                    name: response.data,
                    url: process.env.VUE_APP_IMG_BASE_URL + parseInt(response.data),
                });
                that.mainImageUrl.push(
                    process.env.VUE_APP_IMG_BASE_URL + parseInt(response.data)
                );
            });
            this.noneBtnImg = fileList.length >= this.mainImgLimit;
        },
        //删除图片时
        handleRemoveMainImg(file, fileList) {
            if (file.name) {
                this.deleteImgFileList.push(file.name);
            }
            this.mainImgIds = fileList;
            this.noneBtnImg = fileList.length >= this.mainImgLimit;
        },
        //文件超出个数限制时
        handleExceedMainImg(files, fileList) {
            this.$message.warning(
                `当前限制选择 9 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        //删除图片时
        handleRemoveMainImg(file, fileList) {
            if (file.name) {
                this.deleteImgFileList.push(file.name);
            }
            this.mainImgIds = fileList;
            this.noneBtnImg = fileList.length >= this.mainImgLimit;
        },
    },
};
</script>

<style lang="scss" scoped></style>
